package speculoos.jndi;

import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import speculoos.config.xml.XMLConfigurator;
import speculoos.core.MapperException;
import speculoos.manager.MapperManager;


public class MapperClientTemplateImpl implements MapperClientTemplate {
	private final static Log log = LogFactory
			.getLog(MapperClientTemplateImpl.class);

	private MapperManager mapperManager;

	public MapperClientTemplateImpl(MapperManager mapperManager,XMLConfigurator configurator, String mapFile) {
		this.mapperManager = mapperManager;
		try {
			configurator.parse(Thread.currentThread().getContextClassLoader()
					.getResourceAsStream(mapFile));
			configurator.configure(mapperManager);
			mapperManager.setConfigured();
			mapperManager.start();
		} catch (Exception e) {
			log.error("Error loading MapperClientTemplate:" + e);
		}
	}

	public void add(String mapper, Map input) throws MapperException {
		if(log.isDebugEnabled()) {
			log.debug("add called");
			log.debug(input);
		}
		AddMapper am = (AddMapper) mapperManager.getMapper(mapper);
		try {
			am.add(input, null);
		} finally {
			mapperManager.release(am);
		}
	}
	public void delete(String mapper, Map input) throws MapperException {
		if(log.isDebugEnabled()) {
			log.debug("delete called");
		log.debug(input);
	}
		DeleteMapper dm = (DeleteMapper) mapperManager.getMapper(mapper);
		try {
			dm.delete(input, null);
		} finally {
			mapperManager.release(dm);
		}
	}

	public void modify(String mapper, Map input) throws MapperException {
		if(log.isDebugEnabled()) {
			log.debug("modify called");
		log.debug(input);
	}
		ModifyMapper mm = (ModifyMapper) mapperManager.getMapper(mapper);
		try {
			mm.modify(input, null);
		} finally {
			mapperManager.release(mm);
		}
	}

	public List search(String mapper, Map input) throws MapperException {
		if(log.isDebugEnabled()) {
			log.debug("search called");
		log.debug(input);
	}
		List results = null;
		SearchMapper sm = (SearchMapper) mapperManager.getMapper(mapper);
		try {
			results = sm.search(input, null);
		} finally {
			mapperManager.release(sm);
		}
		return results;
	}
}
